package com.nisco.dms.util.auto;

import java.util.ArrayList;
import java.util.List;

import com.nisco.dms.entity.SqlColumn;
import com.nisco.dms.entity.SqlTable;

/**
 * Entity自动生成
 * 
 * @author Robin. 2013-1-24
 * 
 */
public class EntityAuto {

	private SqlTable sqlTable;
	private List<SqlColumn> columns;
	// private String colName;
	// private String colType;
	// private Integer colSize;
	// private String colPrikey;
	// private String colDes;
	// private Integer tabId;
	// private String memo;
	// private String colNull;
	// 生成的实体名
	private String className = "";
	private String colName = "";
	/**
	 * 构造方法
	 * 
	 * @param sqlTable
	 * @param columns
	 */
	public EntityAuto(SqlTable sqlTable, List<SqlColumn> columns) {
		this.sqlTable = sqlTable;
		this.columns = columns;
	}

	/**
	 * 自动生成实体类
	 */
	public void createEntity() {
		// 用于生成实体类属性的拼接字符创，根据相应的表名及字段名生成实体的类名，属性，set、get方法
		StringBuffer str = new StringBuffer();
		int max = columns.size();

		// 用于将拼接好的字符串传至TextFile.java来替换相应的实体模板参数。
		List<String> list = new ArrayList<String>();

		if (max > 0) {
			for (int i = 0; i < max; i++) {
				if (!columns.get(i).getColName().equals("id")) {
					colName = columns.get(i).getColName();
					colName = WordUtil.spliteWord("_", colName);
					if (columns.get(i).getColNull().equals("N")) {
						str.append("\t@NotBlank\r\n");
						str.append("\t@Column(length = "
								+ columns.get(i).getColSize() + ")\r\n");
					} else {
						str.append("\t@Column(length = "
								+ columns.get(i).getColSize() + ")\r\n");
					}
					String type = (columns.get(i).getColType().split(":")[1]
							.toString());
					String[] subType = type.split("\\.");
					str.append("\tprivate " + subType[2] + " "
							+ colName + ";\r\n");
				}
			}
			for (int i = 0; i < max; i++) {
				if (!columns.get(i).getColName().equals("id")) {
					colName = columns.get(i).getColName();
					colName = WordUtil.spliteWord("_", colName);
					String type = (columns.get(i).getColType().split(":")[1]
							.toString());
					String[] subType = type.split("\\.");
					str.append(WordUtil.setAndGetMethod(colName, subType[2]));
				}
			}
			// 获取模板
			TextFile textFile = new TextFile(
					"src/main/resources/codeTemplate/EntityTemplate.txt");
			list.add("[args]" + "<==>" + str.toString());
			list.add("[tableName]" + "<==>" + sqlTable.getTabName());

			// 根据表名生成实体类名，根据'_'分割，并将分割后的字符串首字母大写
			if (sqlTable.getTabName().toString().contains("_")) {
				String[] classNames = sqlTable.getTabName().split("_");
				for (int i = 1; i < classNames.length; i++) {
					className += WordUtil.firstUpper(classNames[i].toString());
				}
			} else {
				className = WordUtil.firstUpper(sqlTable.getTabName());
			}
			list.add("[className]" + "<==>" + className);
			textFile.write("src/main/resources/autocode/" + className + ".java", list);
		}
	}
}
